﻿using System.Windows.Threading;
using YY.Admin.Core;
using YY.Admin.EventBus;

namespace YY.Admin.Filter
{
    public class GlobalExceptionHandler
    {
        private readonly IErrorHandler _errorHandler;
        private ILoggerService _logger;
        public GlobalExceptionHandler(IErrorHandler errorHandler,
            ILoggerService logger)
        {
            _errorHandler = errorHandler;
            _logger= logger;

            // 注册全局异常处理
           System.Windows.Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            TaskScheduler.UnobservedTaskException += OnUnobservedTaskException!;
        }

        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            _errorHandler.HandleError(e.Exception);
            _logger.Error("未处理的异常", e.Exception);
            e.Handled = true; // 标记为已处理
        }

        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
            {
                _errorHandler.HandleError(ex);
                _logger.Error("UI线程未处理异常", ex);
            }
        }

        private void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            _errorHandler.HandleError(e.Exception);
            _logger.Error("未观察到的任务异常", e.Exception);
            e.SetObserved(); // 标记为已观察
        }
    }
}
